#include "lettershell/shell.h"
#include "global.h"
#include <stdio.h>
#include "bsp/inc/bsp_rtc.h"
#include "bsp/inc/bsp.h"
#include "task_gnss.h"
#include "gnss_power_mgr.h"

#define MINs        (60)
#define HOURs       (60 * MINs)
#define DAYs        (24 * HOURs)

int32_t shell_time_print(int32_t argc, char *argv[])
{
    struct tm tm;
    struct fix_info info = {0};

    if (1 == argc) {
        unsigned int seconds = getsec();
        unsigned int days = seconds / DAYs;
        unsigned int hours = seconds % DAYs / HOURs;
        unsigned int mins = seconds % DAYs % HOURs / MINs;
        unsigned int secs = seconds % DAYs % HOURs % MINs;
        printf("%u seconds (%u days %u:%u:%u) have passed since the system boot.\r\n", seconds,days,hours,mins,secs);
    }
    else if (2 == argc && 4 == strlen(argv[1])) {
        if (0 == strcasecmp(argv[1], "-rtc")) {
            bsp_rtc_get(&tm);
            printf("%04d/%02d/%02d %02d:%02d:%02d\r\n", tm.tm_year, tm.tm_mon, tm.tm_mday,
                                                        tm.tm_hour, tm.tm_min, tm.tm_sec);
        }
        else if (0 == strcasecmp(argv[1], "-utc")) {
            if (FIX_OK == is_gnss_fixed(&info)) {
                memcpy(&tm, &info.utc, sizeof(struct tm));
                printf("%04d/%02d/%02d %02d:%02d:%02d\r\n", tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
                                                            tm.tm_hour, tm.tm_min, tm.tm_sec);
            }
        }
    }
    return 0;
}
 
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN) | SHELL_CMD_DISABLE_RETURN,
                 time, 
                 shell_time_print, 
                 show device time info);

